"""
Case Type   : borrow_memory
Case Name   : alter system set设置max_borrow_memory有效值
Create At   : 2025/4/14
Owner       : @li-xin12345
Description :
    1、设置max_borrow_memory=128MB、256MB、1GB
    2、清理环境
Expect      :
    1、成功
    2、成功
History     :
"""

import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class BorrowMemoryTest(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_db_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.param_name = 'max_borrow_memory'
        self.default_value = self.common.show_param(self.param_name)
        self.param_values = ['128MB', '256MB', '1GB']

    def test_borrow_memory(self):
        text = ('-----step1:设置max_borrow_memory=128MB、256MB、1GB;'
                'expect:成功-----')
        self.log.info(text)
        for value in self.param_values:
            res = self.pri_db_sh.execut_db_sql(
                f'ALTER SYSTEM SET {self.param_name} TO \'{value}\';')
            self.log.info(res)
            self.assertIn(self.constant.ALTER_SYSTEM_SUCCESS_MSG, res,
                          '执行失败：' + text)
            res = self.pri_db_sh.restart_db_cluster()
            self.log.info(res)
            status = self.pri_db_sh.get_db_cluster_status()
            self.assertTrue(res, '执行失败：' + text)
            self.assertTrue("Normal" or "Degrade" in status)
            res = self.common.show_param(self.param_name)
            self.log.info(res)
            self.assertIn(value, res, '执行失败：' + text)

    def tearDown(self):
        text = '-----step2:清理环境; expect:成功-----'
        self.log.info(text)
        res = self.common.show_param(self.param_name)
        self.log.info(res)
        if res != self.default_value:
            res = self.pri_db_sh.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG,
                f"{self.param_name}='{self.default_value}'")
            self.log.info(res)
            res = self.pri_db_sh.restart_db_cluster()
            self.log.info(res)
            status = self.pri_db_sh.get_db_cluster_status()
            self.assertTrue(res, '执行失败：' + text)
            self.assertTrue("Normal" or "Degrade" in status)
            res = self.common.show_param(self.param_name)
            self.log.info(res)
            self.assertEqual(self.default_value, res, '执行失败：' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')